package com.rc.evcharger.netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;

import java.util.HashMap;
import java.util.Map;

/**
 * 单例工具类，保存所有客户端链接
 *
 * @author StevenWang_hjh
 */
public class NettyChannelHandler {
    private static NettyChannelHandler nettyChannelHandler = null;
    private static Map<String, Channel> channelMap = new HashMap<String, Channel>();

    private NettyChannelHandler() {
    }

    public static NettyChannelHandler newInstance() {
        if (nettyChannelHandler == null) {
            nettyChannelHandler = new NettyChannelHandler();
        }
        return nettyChannelHandler;
    }

    public void addChannel(String id, Channel channel) {
        channelMap.put(id, channel);
    }

    public Channel getChannel(String id) {
        return channelMap.get(id);
    }

    public Map<String, Channel> getChannels() {
        return channelMap;
    }

    public void removeChannel(String id) {
        channelMap.remove(id);
    }

    /**
     * 发送消息到客户端
     *
     * @param id
     * @param message
     */
    public void sendMessage(String id, String message) {
        ByteBuf resp = Unpooled.copiedBuffer(message.getBytes());
        Channel channel = getChannel(id);
        if (channel == null) {
            return;
        }
        channel.writeAndFlush(resp);
    }

}
